package com.qk.management.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.role.RoleDTO;
import com.qk.entity.Role;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.service.RoleService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    //根据id删除
    @Override
    public void delete(Integer id) {
        roleMapper.delete(id);
    }

    @Override
    public Role get(Integer id) {
        return roleMapper.selectById(id);
    }

    @Override
    public void update(Role role) {
        //参数校验
        if (role == null) {
            throw new RuntimeException("角色信息不能为空");
        }
        if (StringUtils.isBlank(role.getName())) {
            throw new RuntimeException("角色名称不能为空");
        }
        if (StringUtils.isBlank(role.getLabel())) {
            throw new RuntimeException("角色标识不能为空");
        }
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.update(role);
    }

    @Override
    public List<Role> list() {
        return roleMapper.list();
    }

    @Override
    public void addRole(Role role) {
        // 参数校验
        if (role == null) {
            throw new RuntimeException("角色信息不能为空");
        }

        if (StringUtils.isBlank(role.getName())) {
            throw new RuntimeException("角色名称不能为空");
        }

        if (StringUtils.isBlank(role.getLabel())) {
            throw new RuntimeException("角色标识不能为空");
        }

        // 设置创建时间
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());

        // 调用 DAO 插入数据
        roleMapper.insert(role);
    }

    @Override
    public PageResult<Role> list(RoleDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Role> list = roleMapper.selectByPage(dto);
        Page<Role> page = (Page<Role>) list;
        return PageResult.<Role>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
}
